<template>
  <div class="detail-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-width="100px"
      label-suffix=":"
    >

      <sticky :z-index="10" :class-name="'sub-navbar ' + postForm.color">
        <el-button v-loading="loading" type="success" @click="submitForm">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </sticky>

      <div class="app-container" style="padding: 10px 20px">
        <Warn />
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="基本属性" name="tabBasic">
            <el-row style="margin: 30px">
              <el-col :span="20">
                <el-form-item label="标题" prop="title" required>
                  <el-input v-model.trim="postForm.title" />
                </el-form-item>
                <el-form-item label="子标题">
                  <el-input v-model.trim="postForm.title_sub" />
                </el-form-item>
                <el-form-item label="编码">
                  <el-input v-model.trim="postForm.sn" style="width: 200px" />
                </el-form-item>
                <el-form-item label="起购数量">
                  <el-input v-model.trim="postForm.buy_quantity" style="width: 200px" />
                </el-form-item>
                <el-form-item label="价格" prop="price" required>
                  <el-input v-model="postForm.price" style="width: 200px" />
                </el-form-item>
                <el-form-item label="原价" prop="price_old" required>
                  <el-input v-model="postForm.price_old" style="width: 200px" />
                </el-form-item>
                <el-form-item label="库存">
                  <el-input v-model.number="postForm.stock" style="width: 200px" />
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                  <el-input v-model.number="postForm.sort" style="width: 200px" />
                </el-form-item>
                <el-form-item label="状态">
                  <el-switch
                    v-model="postForm.status"
                    :width="50"
                  />
                </el-form-item>
                <el-form-item label="运营费用" v-if="false">
                  <el-select
                    v-model="postForm.score_cost_id"
                    clearable
                    class="filter-item"
                    placeholder="非积分区商品不要选择"
                  >
                    <el-option
                      v-for="item in scoreCostList"
                      :key="item.id"
                      :label="item.total"
                      :value="item.id"
                    />
                  </el-select>
                  <span style="margin-left: 10px">积分专区需要的运营费用</span>
                </el-form-item>
                <el-form-item label="成本">
                  <el-input v-model="postForm.price_cost" style="width: 200px" />
                </el-form-item>
                <el-form-item label="运费" v-if="false">
                  <el-input v-model="postForm.freight" style="width: 200px" />
                  <span style="margin-left: 10px">偏远地区运费,在系统设置中指定地区</span>
                </el-form-item>
                <el-form-item label="供应商" v-if="false">
                  <el-input v-model="postForm.supplier" style="width: 200px" />
                  <span style="margin-left: 10px">来自哪个供应商</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="margin: 30px">
              <el-col :span="20">
                <el-form-item label="品牌" prop="brand">
                  <el-select
                    v-model="postForm.brand_id"
                    placeholder="品牌"
                    clearable
                    class="filter-item"
                    filterable
                  >
                    <el-option
                      v-for="item in brandList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="平台分类" prop="category">
                  <el-cascader
                    v-model="postForm.category_id"
                    placeholder="请选择分类"
                    clearable
                    class="filter-item"
                    filterable
                    :options="platfromCategoryList"
                    :props="{ checkStrictly: true, label: 'name', value: 'id', emitPath: false }"
                  />
                </el-form-item>
                <el-form-item label="分类" prop="category">
                  <el-cascader
                    v-model="postForm.supplier_category_id"
                    placeholder="请选择分类"
                    clearable
                    class="filter-item"
                    filterable
                    :options="categoryList"
                    :props="{ checkStrictly: true, label: 'name', value: 'id', emitPath: false }"
                  />
                </el-form-item>
                <template v-if="false">
                  <el-form-item label="分区" prop="area">
                    <el-checkbox-group v-model="postForm.area" @change="changeArea">
                      <el-checkbox v-for="area in areaList" :key="area.name" :label="area.name">{{ area.name }}</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                  <p style="color: red; margin-top: 10px; padding-left: 35px">
                    注意: 由于分区规则不同, 只能选择一个分区
                  </p>
                </template>
              </el-col>
            </el-row>
            <el-row style="margin: 30px">
              <el-col :span="20">
                <p style="color: #409EFF;">
                  可以最多上传{{ swiperTotal }}张图片
                </p>
                <p style="color: #409EFF; margin-bottom: 30px">
                  点击 <i class="el-icon-circle-check" /> 可以设置成主图,否则第1张为主图
                </p>
                <el-form-item prop="image" label-width="0">
                  <upload-image
                    bucket="product-swiper"
                    :max="swiperTotal"
                    :width="750"
                    :height="750"
                    :quality="50"
                    :file-list="postForm.image"
                    is-default
                    @onSuccess="onSuccess"
                    @onRemove="onRemove"
                    @setDefault="setDefaultImage"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="margin: 30px">
              <el-col :span="20">
                <p style="color: #409EFF;">
                  注意: 不要和"商品规格"混淆
                </p>
              </el-col>
              <el-col :span="20" style="margin-top: 10px">
                <el-button type="primary" icon="el-icon-circle-plus" @click="addProperty">添加属性</el-button>
              </el-col>
            </el-row>
            <el-row v-for="(item, index) in postForm.property" :key="index">
              <el-col :span="8">
                <el-form-item label="属性名">
                  <el-input v-model.trim="item.name" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="属性值">
                  <el-input v-model.trim="item.value" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-button type="danger" style="margin-left: 10px" @click="removeProperty(index)">删除</el-button>
              </el-col>
            </el-row>
            <el-row style="margin: 30px">
              <el-col :span="24">
                <el-form-item prop="content" style="margin-bottom: 30px;" label-width="0">
                  <Tinymce
                    ref="editor"
                    v-model="postForm.content"
                    :height="400"
                    :quality="50"
                    bucket="product-content"
                    :image-max-width="750"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="margin: 10px 0">
              <el-col :span="20">
                <p style="color: red;">
                  注意: 规格每次修改后, 请到规格管理中重新编辑
                </p>
              </el-col>
            </el-row>
            <el-row style="margin-bottom: 10px">
              <el-col :span="20">
                <el-button type="primary" icon="el-icon-circle-plus" @click="addSku">添加规格</el-button>
                <el-button type="success" icon="el-icon-circle-plus" @click="$router.push(`/product/sku/${id}`)" v-if="isEdit">规格管理</el-button>
              </el-col>
            </el-row>
            <el-row
              v-for="(item, index) in postForm.skuName"
              :key="index + item"
              style="border: 1px solid #eee; padding-top: 20px; border-radius: 10px; margin-bottom: 10px"
            >
              <el-col :span="24">
                <el-form-item label="规格名">
                  <el-input v-model.trim="item.name" clearable style="width: 350px; margin-right: 10px" />
                  <el-button type="danger" @click="removeSku(index)">删除规格</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="规格值">
                  <el-input
                    v-for="(o, i) in item.value"
                    :key="i + o"
                    v-model.trim="o.v"
                    clearable
                    style="width: 150px; margin-right: 10px; margin-bottom: 10px"
                  />
                  <el-button @click="addSkuValue(index)">添加</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-divider />
            <el-row v-for="(item, index) in sku" :key="index" style="margin-bottom: 10px">
              <el-col :span="4" style="text-align: right">
                <el-tag style="margin-right: 10px">{{ item.name }}</el-tag>
              </el-col>
              <el-col :span="20">
                <template v-for="(o, i) in item.value">
                  <el-tag
                    v-if="o.v.length > 0"
                    :key="i"
                    type="danger"
                    closable
                    style="margin-right: 10px; cursor: pointer; margin-bottom: 10px;"
                    @close="removeSkuValue(index, i)"
                  >
                    {{ o.v }}
                  </el-tag>
                </template>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </div>

    </el-form>
  </div>
</template>

<script>
import api from '@/api'
import Sticky from '@/components/Sticky'
import Warn from './Warn'
import UploadImage from '@/components/Upload/UploadImage'
import Tinymce from '@/components/Tinymce'
import config from '@/config'

export default {
  name: 'ProductDetail',
  components: {
    Sticky,
    Warn,
    UploadImage,
    Tinymce
  },
  props: {
    /**
     * 是否为编辑
     */
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    // 标题验证
    const titleValidate = (rule, value, callback) => {
      if (value === undefined || value.length <= 0) {
        this.activeTab = 'tabBasic'
        callback(new Error('请输入名称'))
      } else {
        callback()
      }
    }
    // 排序验证
    const sortValidate = (rule, value, callback) => {
      if (+value < -128 || +value > 127) {
        this.activeTab = 'tabBasic'
        callback(new Error('排序值错误'))
      } else {
        callback()
      }
    }
    // 价格验证
    const priceValidate = (rule, value, callback) => {
      if (+value <= 0) {
        this.activeTab = 'tabBasic'
        callback(new Error('价格错误'))
      } else {
        callback()
      }
    }
    // 原价验证
    const priceOldValidate = (rule, value, callback) => {
      if (+value <= 0 || +value < this.postForm.price) {
        this.activeTab = 'tabBasic'
        callback(new Error('原价错误,必须大于现在的价格'))
      } else {
        callback()
      }
    }
    return {
      activeTab: 'tabBasic',
      id: -1,
      loading: false,
      swiperTotal: 10,
      postForm: {
        // 佣金与差价设置
        commissionDiff: {
          // vip1: 5000,
          // vip2_1: 7000,
          // vip2_2: 2000,
          // vip2_3: 10,
          // svip1_1: 7000,
          // svip1_2: 700,
          // svip1_3: 10,
          // svip2_1: 7000,
          // svip2_2: 1000,
          // svip2_3: 15,
          diff_vip1: 399,
          diff_vip2: 299,
          diff_vip3: 199
          // diff_svip2: 240
        },
        color: 'draft',
        status: true,
        sort: 0,
        image: [],
        category_id: '3',
        price: 0,
        price_old: 0,
        price_cost: 0,
        stock: 10000,
        freight: 0,
        buy_quantity: 1,
        area: [],
        property: [
          { name: '', value: '', id: -1 }
        ],
        skuName: [
          { name: '', value: [{ v: '', id: -1 }, { v: '', id: -1 }, { v: '', id: -1 }, { v: '', id: -1 }], id: -1 }
        ],
        skuList: []
      },
      rules: {
        title: [{ validator: titleValidate, trigger: 'blur' }],
        sort: [{ validator: sortValidate, trigger: 'change' }]
        // price: [{ validator: priceValidate, trigger: 'change' }],
        // price_old: [{ validator: priceOldValidate, trigger: 'change' }]
      },
      // 处理分级分类
      categoryList: [],
      // 平台分类
      platfromCategoryList: [],
      // 分区
      areaList: [],
      // 品牌
      brandList: [],
      // 规格列表
      sku: [],
      // 积分运营费用
      scoreCostList: []
    }
  },
  watch: {
    postForm: {
      handler(v) {
        // 只获取有值的
        this.sku = v.skuName.filter(x => x.name.length > 0 && x.value.filter(y => y.v.length > 0).length > 0)
      },
      deep: true
    }
  },
  created() {
    // 获取编辑数据
    if (this.isEdit) {
      this.id = (this.$route.params && this.$route.params.id) || -1
      this.fetchData(this.id)
    }
    // 分类列表
    this.getCategoryList()
    // 分区列表
    this.getAreaList()
    // 品牌列表
    this.getBrandList()
    this.getScoreCost()
  },
  methods: {
    /**
     * 积分运营费用
     */
    async getScoreCost() {
      const { data } = await api.scoreCost.list()
      this.scoreCostList = data
    },
    // sku
    addSku() {
      const obj = { name: '', value: [{ v: '', id: -1 }, { v: '', id: -1 }, { v: '', id: -1 }, { v: '', id: -1 }], id: -1 }
      this.postForm.skuName.push(obj)
    },
    addSkuValue(index) {
      this.postForm.skuName[index].value.push({ v: '', id: -1 })
    },
    removeSku(index) {
      this.postForm.skuName.splice(index, 1)
    },
    removeSkuValue(index, i) {
      // this.postForm.skuName[index].value.splice(i, 1)
      this.postForm.skuName[index].value[i].v = ''
    },
    // 属性
    addProperty() {
      this.postForm.property.push({
        'name': '',
        'value': '',
        'id': -(1 + this.postForm.property.length)
      })
    },
    removeProperty(index) {
      this.postForm.property.splice(index, 1)
    },
    // 选择分区
    changeArea(v) {
      const area = this.areaList.filter(v => this.postForm.area.includes(v.name)).map(v => v.id)
      // 关闭多选
      if (area.length > 1) {
        this.postForm.area = [this.postForm.area[0]]
        this.$message.warning('分区只能选择一个')
      }
      // 非积分区, 直接改变运营费用为0
      if (area && area.length > 0) {
        if (area[0] !== '2') {
          this.postForm.score_cost_id = 0
        }
      }
    },
    // 品牌
    getBrandList() {
      api.brand.list({ export: true, status: config.brand.OPEN }).then(response => {
        this.brandList = response.data
      })
    },
    /**
     * 分区列表
     */
    getAreaList() {
      api.area.list({ export: true, status: config.area.OPEN }).then(response => {
        this.areaList = response.data
      })
    },
    /**
     * 分类列表
     */
    getCategoryList() {
      // 商家分类
      api.category.tree().then(response => {
        this.categoryList = response.data
      })
      // 平台分类
      api.category.treePlatform().then(response => {
        this.platfromCategoryList = response.data
      })
    },
    /**
     * 获取编辑数据
     */
    async fetchData(id) {
      const response = await api.product.view({ id })
      this.postForm = Object.assign({}, response.data)
      // 状态
      this.postForm.status = +this.postForm.status === 1
      // 分区
      this.postForm.area = this.postForm.area.map(x => x.name.name)
      // 图片
      if (this.postForm.image) {
        const image = this.postForm.image.map(x => x.image)
        let list = []
        image.forEach(x => {
          if (x) {
            list.push({
              id: +x.id,
              url: x.thumbnail_path
            })
          }
        })
        this.postForm.image = [...list]
        // 主图
        if (this.postForm.mainImage) {
          const mainImage = {
            id: +this.postForm.mainImage.id,
            url: this.postForm.mainImage.thumbnail_path
          }
          list = list.filter(x => x.id !== mainImage.id)
          this.postForm.image = [mainImage, ...list]
        }
      } else {
        this.postForm.image = []
      }
      // 属性
      if (this.postForm.properties) {
        this.$set(this.postForm, 'property', [...this.postForm.properties])
      }
      // sku
      if (this.postForm.skuName) {
        const list = []
        this.postForm.skuName.forEach(x => {
          const item = {
            id: x.id,
            name: x.name,
            value: []
          }
          if (x.values) {
            x.values.forEach(y => {
              if (y.value) {
                item.value.push({ v: y.value, id: y.id })
              }
            })
          }
          list.push(item)
        })
        this.postForm.skuName = [...list]
      }
      // 分类, 类型转换
      this.$set(this.postForm, 'category_id', '' + this.postForm.category_id)
      this.$set(this.postForm, 'price', +this.postForm.price)
      this.$set(this.postForm, 'price_old', +this.postForm.price_old)
      this.$set(this.postForm, 'price_cost', +this.postForm.price_cost)
    },
    /**
     * 提交表单
     */
    submitForm() {
      this.$refs.postForm.validate(valid => {
        // 运营费用
        if (!this.postForm.score_cost_id) {
          this.postForm.score_cost_id = 0
        }
        // 不让多选分区
        if (this.postForm.area.length > 1) {
          return this.$message.warning('分区只能选择一个')
        }
        if (valid) {
          this.loading = true
          // 状态
          const status = this.postForm.status ? 1 : 0
          // 图片
          let image = []
          if (this.postForm.image.length > 0) {
            image = this.postForm.image.map(x => x.id)
          }
          // 分区
          // const area = this.areaList.filter(v => this.postForm.area.includes(v.name)).map(v => v.id)
          const area = [3]
          api.product.edit({
            id: this.id,
            ...this.postForm,
            status,
            image,
            // area_id: area.join(',')
            area_id: area,
            sku: this.sku
          }).then(response => {
            this.loading = false
            this.$notify({
              title: '成功',
              message: response.message || '操作成功',
              type: 'success',
              duration: 2000
            })
            // 一定要加时间戳去缓存, 否则sku容易出错
            // this.$router.push(`/product/edit/${response.data.id}?t=${new Date().getTime()}`)
            if (!this.isEdit) {
              // this.$router.push(`/product/edit/${response.data.id}`)
            }
            // 还是跳到list能彻底解决
            // 客户要求退回
            // this.$router.push('/product/list')
            this.$router.go(-1)
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    /**
     * 图片上传
     */
    onSuccess(data, fileList) {
      if (data && data.id) {
        this.postForm.image.push({
          id: data.id,
          url: data.thumbnail
        })
      }
    },
    /**
     * 删除图片
     */
    onRemove(data) {
      if (data && data.id) {
        this.postForm.image = this.postForm.image.filter(x => x.id !== data.id)
      }
    },
    /**
     * 设置默认图片
     */
    setDefaultImage(data) {
      // console.log(data, this.postForm.image)
      if (data && data.id) {
        this.postForm.image = this.postForm.image.filter(x => x.id !== data.id)
        // this.postForm.image = [data, ...this.postForm.image]
        this.postForm.image.unshift(data)
        // console.log(this.postForm.image)
        this.$message({
          message: '设置成功',
          type: 'success'
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.detail-container {
  //
}
</style>
